/*
 * @Author: 0x9DEFA478
 * @Date: 2025-01-07 15:56:21
 * @LastEditTime: 2025-10-03 22:39:56
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * 
 */
#include "./H_Concurrency_win.hpp"
#ifdef _WIN32
#include "SystemAPI/Windows/Error.hpp"
#include <string>
#include <stdexcept>
#include <windows.h>
#endif




namespace H{

  namespace Concurrency{

#ifdef _WIN32
    Event_win::Event_win(){
      E=CreateEvent(nullptr,FALSE,FALSE,nullptr);
      if(E==nullptr){
        throw std::runtime_error("Event_win::Event_win() Fail: "+SystemAPI::Windows::GetErrorString());
      }
    }
    Event_win::~Event_win()noexcept{
      CloseHandle(E);
    }

    void Event_win::Acquire()noexcept{
      WaitForSingleObject(E,INFINITE);
    }

    bool Event_win::Acquire(usize Timeout)noexcept{
      return WaitForSingleObject(E,Timeout)==WAIT_OBJECT_0;
    }

    bool Event_win::Acquire_us(usize Timeout)noexcept{
      if(Timeout>1000){
        return WaitForSingleObject(E,Timeout/1000)==WAIT_OBJECT_0;
      }
      return WaitForSingleObject(E,1)==WAIT_OBJECT_0;
    }

    void Event_win::Trigger()noexcept{
      SetEvent(E);
    }


    Lock_win::Lock_win(){
      L=CreateMutex(nullptr,false,nullptr);
      if(L==nullptr){
        throw std::runtime_error("Lock_win::Lock_win() Fail: "+SystemAPI::Windows::GetErrorString());
      }
    }

    Lock_win::~Lock_win()noexcept{
      CloseHandle(L);
    }

    void Lock_win::Lock()noexcept{
      WaitForSingleObject(L,INFINITE);
    }
    
    void Lock_win::Unlock()noexcept{
      ReleaseMutex(L);
    }
#endif

  }
}



